package com.mhxy.util;

import cn.hutool.core.util.StrUtil;
import com.mhxy.constant.PicConstants;
import com.mhxy.handler.ConfigHandler;
import com.sun.jna.platform.win32.WinDef;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CommandUtil {
    private static Logger LOG = LoggerFactory.getLogger(CommandUtil.class);

    public static void exec(String command) {
        try {
            Runtime.getRuntime().exec(command);
        } catch (Exception e) {
            System.out.println("执行CMD失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void openGameByBox(String boxName) throws Exception {
        // 检测窗口是否以打开
        WinDef.HWND luncherHwnd = HwndUtil.getByName(boxName);
        if (luncherHwnd != null) {
            LOG.info("窗口: {} 已再开，不再重复打开！", boxName);
            return;
        }

        String command1 = StrUtil.format("\"{}\" /box:{} \"{}\"", ConfigHandler.getBoxUrl(), boxName, ConfigHandler.getGameUrl());
        CommandUtil.exec(command1);
        System.out.println("打开游戏窗口: " + boxName);
        ThreadUtil.sleep(5000);

        luncherHwnd = getStartHwnd(boxName);

        if (!FuzzyPicUtil.findAndClickRandom(luncherHwnd, PicConstants.开始游戏_开始游戏)) {
            // 防止周三登录更新 这里运行2次保险
            if (!FuzzyPicUtil.findAndClickRandom(luncherHwnd, PicConstants.开始游戏_开始游戏)) {
                LOG.error("窗口 {} 打开失败！", boxName);
                throw new RuntimeException("窗口打开失败");
            }
        }
    }

    private static WinDef.HWND getStartHwnd(String boxName) throws Exception {
        for (int i =  0; i < 20; i++) {
            ThreadUtil.sleep3();
            WinDef.HWND luncherHwnd = HwndUtil.getMyPCLauncher(boxName);
            if (luncherHwnd != null) {
                return luncherHwnd;
            }
        }
        throw new RuntimeException("没有找到MyPCLauncher_x64r句柄: " + boxName);
    }
}
